﻿# -*- coding: utf-8 -*-  
import cgi
import os
import Database
from Database import *
import time
import random
import feedparser
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext.db import *
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import run_wsgi_app


	
class MainPage(webapp.RequestHandler):
  def get(self):
	tree_query = Database.Tree.all()
	trees = tree_query
	userdata_query = Database.UserData.gql("ORDER BY createdate DESC LIMIT 10 OFFSET 0")
	userdatas = userdata_query
	

	if users.get_current_user():
	  url = users.create_logout_url(self.request.uri)
	  url_linktext = 'Logout'
	else:
	  url = users.create_login_url(self.request.uri)
	  url_linktext = 'Login'

	template_values = {
	  'trees': trees,
	  'userdatas': userdatas,
	  'url': url,
	  'ip':self.request.remote_addr,
	  'url_linktext': url_linktext,
	  }

	path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
	self.response.out.write(template.render(path, template_values))


class Guestbook(webapp.RequestHandler):
  def post(self):
    greeting = Database.Greeting()

    if users.get_current_user():
      greeting.author = users.get_current_user()

    greeting.content = self.request.get('content')
    greeting.put()
    self.redirect('/')

class addTree(webapp.RequestHandler):
  def post(self):
    greeting = Database.Tree()

    greeting.text = self.request.get('content')
    greeting.put()
    self.redirect('/tree')

class addData(webapp.RequestHandler):
	def post(self):
		rss = Database.UserData()
		rss.title = self.request.get('title')
		rss.content = self.request.get('content')
		rss.typeid = Database.Tree(int(self.request.get('treeid')))
		rss.put()
		self.redirect('/getrss/'+self.request.get('treeid'))

class addRss(webapp.RequestHandler):
	def post(self):
		obj = Database.Tree.get_by_id(int(self.request.get('treeid')))
		query = Database.Tree.all()
		query.ancestor(obj)
		task = query.get()	
		rss = Database.Rss()
		rss.title = self.request.get('title')
		rss.url = self.request.get('url')
		rss.tree = task
		rss.put()
		self.redirect('/getrss/'+self.request.get('treeid'))

class getData(webapp.RequestHandler):
  def get(self,id):
    userdata_query = Database.UserData.all()
    userdatas = userdata_query

    template_values = {
      'userdatas': userdatas,
	  'typeid':id
	}

    path = os.path.join(os.path.dirname(__file__), 'templates/userdata.html')
    self.response.out.write(template.render(path, template_values))

class getRss(webapp.RequestHandler):
	def get(self,id):
		obj = Database.Tree.get_by_id(int(id))
		query = Database.Tree.all()
		query.ancestor(obj)
		task = query.get()
		
		rss=Database.Rss.all()
		rss.filter('tree = ',task)

		template_values = {
		  'rsss': rss,
		  'treeid':id
		}
		
		path = os.path.join(os.path.dirname(__file__), 'templates/getrss.html')
		self.response.out.write(template.render(path, template_values))
	
class GuestTree(webapp.RequestHandler):
  def get(self):
    greetings_query = Database.Tree.all()
    greetings = greetings_query

    template_values = {
      'greetings': greetings  
	}

    path = os.path.join(os.path.dirname(__file__), 'templates/tree.html')
    self.response.out.write(template.render(path, template_values))

class test(webapp.RequestHandler):
	def post(self):
		 self.response.out.write("<html><body><p>hello,caoyue</p></body></html>")
		 
class admin1(webapp.RequestHandler):
	def get(self):
		template_values = {
			'greetings': '1'  
		}
		path = os.path.join(os.path.dirname(__file__), 'templates/admin.html')
		self.response.out.write(template.render(path, template_values))

class login(webapp.RequestHandler):
	def post(self):
		if (self.request.get('u')=='caoyueqq@163.com'):
			self.response.out.write('{"success":"True"}')
		else:
			self.response.out.write('{"success":"False"}')
		
class BrowseHandler(webapp.RequestHandler):
	def get(self, category, product_id,pageno):
		self.response.out.write("<html><body><p>type="+category+"<br/>id="+product_id+"<br/>pageno="+pageno+"</p></body></html>")

		
class getType(webapp.RequestHandler):
	def get(self, tno):
		obj = Database.Tree.get_by_id(int(tno))
		query = Database.Tree.all()
		query.ancestor(obj)
		task = query.get()
		tree_query = Database.Tree.all()
		trees = tree_query
		userdata_query = Database.UserData.all().order('-createdate')
		userdata_query.filter('tree1 = ',task)
	
		template_values = {
			'trees': trees,
			'userdatas': userdata_query
		}

		path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
		self.response.out.write(template.render(path, template_values))		
		
class getUrl(webapp.RequestHandler):
	def get(self,strurl):
		try:
			urlfetch.allow_truncated=True
			result = urlfetch.fetch('http://'+strurl)
			
			if result.status_code == 200:			
				self.response.out.write(result.content.decode('gb2312','replace'))
		except:
			self.response.out.write(strurl)

class page(webapp.RequestHandler):
	def get(self, pno=1):
		tree_query = Database.Tree.all()
		trees = tree_query
		inta=10*int(pno)
		userdata_query = Database.UserData.all().order('-createdate').fetch(inta,inta-10)[0:10]
		userdatas = userdata_query

		if users.get_current_user():
		  url = users.create_logout_url(self.request.uri)
		  url_linktext = 'Logout'
		else:
		  url = users.create_login_url(self.request.uri)
		  url_linktext = 'Login'
			
		template_values = {
			'trees': trees,
			'userdatas': userdatas,
			'url': url,
			'url_linktext': url_linktext,
		  }

		path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
		self.response.out.write(template.render(path, template_values))
		
class summary(webapp.RequestHandler):
	def get(self):
		query = Database.Rss.all()
		intid = random.randint(0,query.count())
		rss=feedparser.parse(query[intid].url)
		query11 = Database.UserData.all()
		
		for items in rss.entries:
			try:
				items=map(format,[items.title,items.link,items.date,items.description])
				for title in query11:
					if title==items[0]:
						break
						return
				if len(items[3].strip())>0:		
					userdata2 = Database.UserData()				
					userdata2.title = items[0]
					#userdata1.content = result.content.decode('utf8','replace')
					userdata2.tree1 = query[intid].tree
					#userdata2.updatedate=items[2]
					userdata2.url = items[1]
					userdata2.content = items[3]
					userdata2.typeid = '11'
					userdata2.put()
			except:
				self.response.out.write("error:"+query[intid].url.encode('utf-8'))
				
		self.response.out.write(query[intid].url.encode('utf-8'))
		
application = webapp.WSGIApplication([
					('/', MainPage),
					('/sign', Guestbook),
					('/tree', GuestTree),
					(r'/getrss/(.*)', getRss),
					(r'/type/(.*)', getType),
					('/addtree', addTree),
					(r'/data/(.*)', getData),
					('/adddata', addData),
					('/addrss', addRss),
					('/tasks', summary),
					('/test', test),
					(r'/url/(.*)', getUrl),
					(r'/(.*)', page),
					('/admin', admin1),
					('/login', login),

					(r'/(.*)/(.*)/(.*)', BrowseHandler)
				],debug=True)


def format (target):
	'''format the string take out \r\n and blank space'''
	target=target.replace("\n","")
	target=target.replace("\r","")
	target=target.replace("\\","\\\\")
	target=target.replace("\'","\\'")
	return target 
		
def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()